<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/6/25
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper;


use paper\http\Request;
use paper\http\Response;
use paper\log\Log;
use paper\providers\ExceptionServiceProvider;
use paper\providers\LogServiceProvider;
use paper\routing\Router;
use paper\session\Session;
use paper\support\ServiceProvider;
use paper\tplLibs\Engine;


class App extends Container
{
    public function __construct()
    {
        static::setInstance($this);
        $this->registerCoreContainerService();

        $this->instance("app", $this);

        $this->registerBaseServiceProviders();
        $this->registerConfiguredProviders();


    }

    /**
     * 加载配置文件中的服务提供者
     */
    protected function registerConfiguredProviders()
    {
        if ($this->config->app('providers')) {
            foreach ($this->config->app('providers') as $providers) {
                $this->register(new $providers($this));
            }
        }
    }

    /**
     * 注册基本服务提供者
     */
    protected function registerBaseServiceProviders()
    {
        $this->app->bind(Config::class, new Config());
        $this->register(new ExceptionServiceProvider($this));
        $this->register(new LogServiceProvider($this));
    }

    /**
     *  注册核心服务类到容器中
     */
    protected function registerCoreContainerService()
    {
        $aliases = [
            'app'        => App::class,
            'config'     => Config::class,
            'cookie'     => Cookie::class,
            'log'        => Log::class,
            'request'    => Request::class,
            'response'   => Response::class,
            'router'     => Router::class,
            'session'    => Session::class,
            'url'        => Url::class,
            'view'       => View::class,
            'middleware' => Middleware::class,
            'kernel'     => Kernel::class,
            'engine'     => Engine::class,
        ];

        $this->alias($aliases);

    }

    public function register(ServiceProvider $provider)
    {
        if (method_exists($provider, 'register')) {
            $provider->register();
        }
    }
}